﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace AdbRegisterUtils
{
    public class FileOperationService
    {
        /// <summary>
        /// 从文件加载寄存器配置
        /// </summary>
        public bool LoadRegisterConfigFromFile(string filePath, out List<AddrHelp> operations, out uint addr, out uint addrV)
        {
            operations = new List<AddrHelp>();
            addr = 0;
            addrV = 0;

            try
            {
                using (var reader = new StreamReader(filePath, Encoding.GetEncoding("gb2312")))
                {
                    while (!reader.EndOfStream)
                    {
                        string line = reader.ReadLine();
                        if (string.IsNullOrEmpty(line)) continue;

                        line = line.Trim();

                        // 处理注释
                        if (line.Contains("//"))
                            line = line.Remove(line.IndexOf("//"));

                        line = line.Replace('，', ',').Replace(" ", "");

                        if (string.IsNullOrEmpty(line)) continue;

                        string[] values = line.Split(',');

                        if (values.Length >= 2)
                        {
                            string addrStr = values[0].Trim();
                            string dataStr = values[1].Trim();

                            if (string.IsNullOrEmpty(addrStr) || string.IsNullOrEmpty(dataStr))
                                continue;

                            // 处理 0x 前缀
                            if (addrStr.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
                                addrStr = addrStr.Substring(2);
                            if (dataStr.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
                                dataStr = dataStr.Substring(2);

                            uint regAddress = Convert.ToUInt32(addrStr, 16);
                            uint regData = Convert.ToUInt32(dataStr, 16);

                            if (regAddress == 0xfffd)
                            {
                                addr = (regData & 0xff);
                            }
                            else if (regAddress == 0xfffe)
                            {
                                addrV = (regData & 0xff);
                            }
                            else
                            {
                                var model = new AddrHelp(regAddress, regData)
                                {
                                    BaseAddr = (addr << 8) + (addrV & 0xff)
                                };
                                operations.Add(model);
                            }
                        }
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"加载寄存器配置文件时出错: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 从文件加载 I2C 配置
        /// </summary>
        public bool LoadI2CConfigFromFile(string filePath, out List<SensorHelp> operations, out uint sensorId)
        {
            operations = new List<SensorHelp>();
            sensorId = 0;

            try
            {
                using (var reader = new StreamReader(filePath, Encoding.GetEncoding("gb2312")))
                {
                    while (!reader.EndOfStream)
                    {
                        string line = reader.ReadLine();
                        if (string.IsNullOrEmpty(line)) continue;

                        line = line.Trim();

                        // 处理注释
                        if (line.Contains("//"))
                            line = line.Remove(line.IndexOf("//"));

                        line = line.Replace('，', ',').Replace(" ", "");

                        if (string.IsNullOrEmpty(line)) continue;

                        string[] values = line.Split(',');

                        if (values.Length >= 2)
                        {
                            string addrStr = values[0].Trim();
                            string dataStr = values[1].Trim();

                            if (string.IsNullOrEmpty(addrStr) || string.IsNullOrEmpty(dataStr))
                                continue;

                            // 处理 0x 前缀
                            if (addrStr.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
                                addrStr = addrStr.Substring(2);
                            if (dataStr.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
                                dataStr = dataStr.Substring(2);

                            uint regAddress = Convert.ToUInt32(addrStr, 16);
                            uint regData = Convert.ToUInt32(dataStr, 16);

                            if (regAddress == 0xfff8)
                            {
                                sensorId = (regData & 0xff);
                            }
                            else if (regAddress != 0xfff2 && regAddress != 0xfffe && regAddress != 0xffff)
                            {
                                var model = new SensorHelp(regAddress, regData)
                                {
                                    ID = sensorId.ToString("X2")
                                };
                                operations.Add(model);
                            }
                        }
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"加载I2C配置文件时出错: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 保存寄存器配置到文件
        /// </summary>
        public bool SaveRegisterConfigToFile(List<AddrHelp> operations, string destinationPath)
        {
            try
            {
                using (var writer = new StreamWriter(destinationPath, false, Encoding.GetEncoding("gb2312")))
                {
                    string currentBaseAddr = string.Empty;
                    foreach (var item in operations)
                    {
                        string baseAddrStr = item.BaseAddr.ToString("X");
                        if (string.IsNullOrEmpty(currentBaseAddr) || currentBaseAddr != baseAddrStr)
                        {
                            writer.WriteLine($"0xfffd,0x{(item.BaseAddr >> 8 & 0xff).ToString("X2")},");
                            writer.WriteLine($"0xfffe,0x{(item.BaseAddr & 0xff).ToString("X2")},");
                            currentBaseAddr = baseAddrStr;
                        }
                        writer.WriteLine($"0x{item.Address.ToString("X4")},0x{item.Data.ToString("X2")},");
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"保存寄存器配置文件时出错: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 保存 I2C 配置到文件
        /// </summary>
        public bool SaveI2CConfigToFile(List<SensorHelp> operations, string destinationPath)
        {
            try
            {
                using (var writer = new StreamWriter(destinationPath, false, Encoding.GetEncoding("gb2312")))
                {
                    string currentId = string.Empty;
                    foreach (var item in operations)
                    {
                        if (string.IsNullOrEmpty(currentId) || currentId != item.ID)
                        {
                            writer.WriteLine($"0xfff8,0x{item.ID},");
                            currentId = item.ID;
                        }
                        writer.WriteLine($"0x{item.Address.ToString("X4")},0x{item.Data.ToString("X2")},");
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"保存I2C配置文件时出错: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 打开文件对话框选择文件 - 使用完整限定名避免冲突
        /// </summary>
        public string OpenFileDialog(string filter = "TXT Files(*.txt)|*.txt|All Files(*.*)|*.*")
        {
            try
            {
                using (System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog())
                {
                    openFileDialog.Filter = filter;
                    System.Windows.Forms.DialogResult result = openFileDialog.ShowDialog();
                    return result == System.Windows.Forms.DialogResult.OK ? openFileDialog.FileName : null;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"打开文件对话框时出错: {ex.Message}");
                return null;
            }
        }

        /// <summary>
        /// 获取桌面路径
        /// </summary>
        public string GetDesktopPath()
        {
            return Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
        }
    }
}